import { join, resolve } from 'node:path'
import { getExportsSize } from 'export-size'
import { filesize } from 'filesize'
import fs from 'fs-extra'
import { packages } from '../meta/packages'
import { version } from '../package.json'

async function run() {
  // made shared library imported can resolve correctly
  const packagesRoot = resolve(__dirname, '..', 'packages')
  await fs.copy(
    join(packagesRoot, 'solid-to-vue/dist'),
    join(packagesRoot, 'shared/dist/node_modules/@solidjs-use/solid-to-vue'),
    {
      overwrite: true
    }
  )
  await fs.copy(join(packagesRoot, 'shared/dist'), join(packagesRoot, 'core/dist/node_modules/@solidjs-use/shared'), {
    overwrite: true
  })
  let md = '# Export size\n\n'
  const mdJSON: Record<string, string> = {}
  md += 'generated by [export-size](https://github.com/antfu/export-size)<br />\n'
  md += `version: ${version}<br />\n`
  md += `date: ${new Date().toISOString()}\n\n`

  md += '> Please note this is bundle size for each individual APIs (excluding solid-js). '
  md += 'Since we have a lot shared utilities underneath each function, importing two '
  md += 'different functions does NOT necessarily mean the bundle size will be the sum of them (usually smaller). '
  md += 'Depends on the bundler and minifier you use, the final result might vary, this list is for reference only.'
  md += '\n\n'

  for await (const pkg of [...packages.slice(2), packages[1]]) {
    const { exports, packageJSON } = await getExportsSize({
      pkg: `./packages/${pkg.name}`,
      output: false,
      bundler: 'rollup',
      external: ['solid-js', ...(pkg.external ?? [])],
      includes: ['@solidjs-use/shared']
    })

    md += `## ${packageJSON.name}\n`

    const table = `
<Table>
  <Thead>
    <Tr>
      <Th style='width: 50%'>Function</Th>
      <Th>min+gzipped</Th>
    </Tr>
  </Thead>
  <Tbody>
${exports
  .map(item => {
    mdJSON[item.name] = String(filesize(item.minzipped))
    return `    <Tr>
      <Td><code>${item.name}</code></Td>
      <Td>${mdJSON[item.name]}</Td>
    </Tr>`
  })
  .join('\n')}
  </Tbody>
</Table>`
    md += table

    md += '\n'
  }

  await fs.writeFile('packages/docs/src/pages/export-size.md', md, 'utf-8')
  await fs.writeJSON('packages/docs/src/data/export-size.json', mdJSON, { spaces: 2 })
}

run()
